//
//  CZPushCommentViewController.swift
//  GZWeibo007
//
//  Created by 颜祥 on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import AFNetworking
import SnapKit
import SVProgressHUD
/*
对一条微博进行评论:
URL:https://api.weibo.com/2/comments/create.json
请求方式:POST
请求参数:
access_token:String 采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得
comment:String 评论内容，必须做URLencode，内容不超过140个汉字
id:Int64 需要评论的微博ID

*/

class CZPushCommentViewController: UIViewController,UITextViewDelegate
{
    //MARK:-- 属性
    var status: CZStatus?
    
    var vc: CZPushViewController?{
        didSet{
            status = vc?.status
            commemts = vc?.commentes
        }
    }
    
    // 评论数组
    var commemts: [CZcommentModel]?
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        let animation = CABasicAnimation(keyPath: "transform.rotation.y")
        animation.fromValue = (-M_PI)
        animation.removedOnCompletion = false
        animation.fillMode = kCAFillModeForwards;
        animation.duration = 1.0;
        self.view.layer.addAnimation(animation, forKey: nil);
    }
    
    override func viewDidLoad()
    {
        // 添加导航条按钮
        setupNavigationBarButton()
        automaticallyAdjustsScrollViewInsets = false
        // 添加输入框
        view.addSubview(writeTextField)
        // 添加约束
        addWriteTextFieldConstraint()
        
       writeTextField.becomeFirstResponder()
        sendButton.enabled = false
        view.backgroundColor = UIColor(white: 0.9, alpha: 1)
    }
    
    
    // 添加输入框约束
    private func addWriteTextFieldConstraint()
    {
        
        writeTextField.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view).offset(100)
            make.leading.trailing.equalTo(view)
            make.height.equalTo(200)
        }
        
        
//        writeTextField.translatesAutoresizingMaskIntoConstraints = false
//        // 顶部
//        view.addConstraint(NSLayoutConstraint(item: writeTextField, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 64))
//        // 左
//        view.addConstraint( NSLayoutConstraint(item: writeTextField, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 8))
//        // 右
//        view.addConstraint(NSLayoutConstraint(item: writeTextField, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: -8))
//        // 底部
//        view.addConstraint( NSLayoutConstraint(item: writeTextField, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 50))
        
    }
    
    // 添加导航条按钮
    private func setupNavigationBarButton()
    {
        // 添加导航条按钮
        // 取消
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        
        // 发送
        sendButton.frame = CGRect(x: 0, y: 0, width: 45, height: 25)
        sendButton.layer.masksToBounds = true
        sendButton.layer.cornerRadius = 5
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        
    }
    
    // MARK: - 按钮点击事件
    // 点击取消
    func cancel()
    {
        dismissViewControllerAnimated(false, completion: nil)
    }
    
    // 点击发送
    func send()
    {
        // 获得writeTextField内容
         let comment = writeTextField.text!
        print("评论的内容: \(comment)")
        
        // 请求数据应该交给专门的网络工具去执行
        
        // 跳转到指定界面,将text回传
        
        // 获得access_token:String
        
        // 获得comment:String
        
        // 获得id: Int64 微博模型的id,获取微博模型
        
        // 将评论加入到评论模型数组中，传递给
       
            // 获得模型
            CZNetworkTool.sharedInstance.creatComment(comment, id: status!.id) { (result, error) -> () in
                
                if error != nil && result == nil
                {
                    print("创建评论失败")
                    return
                }
                
                // 创建评论模型
                print("result: \(result!)")
                
                //let commentModel = CZcommentModel(dict: result!)
                
                // 将评论模型添加到评论模型数组中
//                self.commemts?.insert(commentModel, atIndex: 0)
                
                // 跳转控制器
//                vc.status = self.status
                
                self.dismissViewControllerAnimated(false, completion:{ ()->Void in
                    self.vc!.loadNewComment()
                })
                
                
            }
        
     }
    
    // MARK: - 懒加载输入框
    private lazy var writeTextField: UITextView =
    {
        let writeTextField = UITextView()
        writeTextField.delegate = self
        
        writeTextField.backgroundColor = UIColor.redColor()
        writeTextField.font = UIFont.systemFontOfSize(16)
        //writeTextField.placeHodler.text = "说说分享心得..."
        //writeTextField.placeHodler.backgroundColor = UIColor.redColor()
        writeTextField.layer.cornerRadius = 8
        writeTextField.layer.masksToBounds = true
        
        // 监听writeTextField文本内容的改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "writeTextFieldValueChange", name: UITextViewTextDidChangeNotification, object: writeTextField)
        return writeTextField
    }()
    
    // 发送按钮
    private lazy var sendButton: UIButton =
    {
        let sendButton = UIButton(type: UIButtonType.Custom)
        sendButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        sendButton.setTitle("发送", forState: UIControlState.Normal)
        sendButton.titleLabel?.font = UIFont.systemFontOfSize(13)
        sendButton.enabled = false
        sendButton.addTarget(self, action: "send", forControlEvents: UIControlEvents.TouchUpInside)
        
        
        return sendButton
        
    }()
    
    var label: UILabel = {
        let label = UILabel()
        label.text = "正在输入中..."
        label .sizeToFit()
        return label
    }()
    
    // 监听文本输入框文本的变化
    func writeTextFieldValueChange()
    {
        print("正在输入")
        
        
        
        self.navigationItem.titleView = label
        let animation = CABasicAnimation(keyPath: "transform.scale")
        animation.fromValue = (0.8)
        animation.toValue = (1.0)
        animation.duration = 1.0
        animation.repeatCount = MAXFLOAT
        label.layer .addAnimation(animation, forKey: nil)
        
        sendButton.enabled = writeTextField.text?.characters.count == 0 ? false : true
        
        // 如果有文本,writeTextField.placeHodler就隐藏
        //writeTextField.placeHodler.hidden = writeTextField.text?.characters.count == 0 ? false : true
        
    }
    
    // 字数限制
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        
        if range.location > 140
        {
            sendButton.enabled = false
            
            // 字数超过140
            SVProgressHUD.showInfoWithStatus("字数超过140", maskType: SVProgressHUDMaskType.Black)
            
            return false
        }
        return true
    }
}
